package com.soul.doc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soul.common.exception.BaseException;
import com.soul.doc.bean.dto.CollectionDto;
import com.soul.doc.bean.po.HistoryPo;
import com.soul.doc.mapper.HistoryMapper;
import com.soul.doc.service.HistoryService;
import com.soul.common.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 历史记录 服务实现类
 * </p>
 *
 * @author sws
 * @since 2023-12-06 16:32:35
 */
@Service
public class HistoryServiceImpl extends BaseService<HistoryMapper, HistoryPo> implements HistoryService {
    @Override
    public void addHistory(CollectionDto collectionDto){
        if (!StpUtil.isLogin()){
            throw new BaseException("未登录");
        }
        long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
        HistoryPo loveMusicPo = new HistoryPo();
        loveMusicPo.setMusicId(collectionDto.getMusicId())
                .setUserId(userId);
        Long maxSort = this.getMaxSort(HistoryPo::getUserId, userId);
        loveMusicPo.setSort(maxSort);
        this.save(loveMusicPo);
    }

    @Override
    public List<HistoryPo> getHistory(Integer size){
        long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
        Page<HistoryPo> page = new Page<>(1,size);
        Page<HistoryPo> historyPoPage = this.getLambadaQueryWrapper()
                .select(HistoryPo::getMusicId,HistoryPo::getMusicCount)
                .eq(HistoryPo::getUserId, userId)
                .groupBy(HistoryPo::getMusicId)
                .page(page);
        return historyPoPage.getRecords();
    }
}
